// Token管理工具
export class TokenManager {
  static getToken() {
    return localStorage.getItem('token')
  }

  static setToken(token) {
    localStorage.setItem('token', token)
    console.log('✅ Token已保存')
  }

  static removeToken() {
    localStorage.removeItem('token')
    localStorage.removeItem('user_info')
    localStorage.removeItem('auth')
    console.log('🗑️ Token已清除')
  }

  static isTokenValid() {
    const token = this.getToken()
    if (!token) {
      console.log('❌ 没有Token')
      return false
    }

    try {
      const parts = token.split('.')
      if (parts.length !== 3) {
        console.log('❌ Token格式错误')
        return false
      }

      const payload = JSON.parse(atob(parts[1]))
      const now = Math.floor(Date.now() / 1000)

      if (payload.exp && payload.exp < now) {
        console.log('❌ Token已过期')
        return false
      }

      console.log('✅ Token有效')
      return true
    } catch (error) {
      console.log('❌ Token验证失败:', error)
      return false
    }
  }

  static getTokenInfo() {
    const token = this.getToken()
    if (!token) return null

    try {
      const parts = token.split('.')
      const payload = JSON.parse(atob(parts[1]))
      
      return {
        userId: payload.userId,
        username: payload.username,
        role: payload.role,
        exp: payload.exp,
        iat: payload.iat,
        expDate: new Date(payload.exp * 1000).toLocaleString(),
        iatDate: new Date(payload.iat * 1000).toLocaleString()
      }
    } catch (error) {
      console.error('解析Token失败:', error)
      return null
    }
  }

  static refreshTokenIfNeeded() {
    if (!this.isTokenValid()) {
      console.log('🔄 Token无效，需要重新登录')
      window.location.href = '/login'
      return false
    }
    return true
  }
}

// 在控制台中可以使用的调试工具
window.TokenManager = TokenManager
window.debugToken = () => {
  console.log('=== Token调试信息 ===')
  console.log('Token存在:', !!TokenManager.getToken())
  console.log('Token有效:', TokenManager.isTokenValid())
  console.log('Token信息:', TokenManager.getTokenInfo())
  console.log('==================')
}

console.log('🔧 Token管理工具已加载，使用 debugToken() 查看Token状态')
